package android.slc.user.ui.dept.vmbox

import android.slc.adapter.LoadMoreDataFormat3
import android.slc.adapter.PageModel
import android.slc.appbase.api.slc.callback.SlcObserver
import android.slc.appbase.ui.vd.wrapper.BaseListPageWrapper
import android.slc.appbase.ui.vd.wrapper.IBaseListPageWrapper
import android.slc.core.domain.BundleBuilder
import android.slc.extras.component.tree.config.ConstantsTree
import android.slc.extras.component.tree.ui.TreeListVmBox
import android.slc.extras.user.entity.SysDept
import android.slc.extras.user.repository.remote.DeptServiceRepository

/**
 *
 * @Description:
 * @Author: sunlunchang
 * @CreateDate: 2021/12/06 下午 2:42
 *
 */
abstract class DeptListVmBox : TreeListVmBox<SysDept>(),
    IBaseListPageWrapper<SysDept> {
    private val baseListPageWrapper: BaseListPageWrapper<SysDept>

    init {
        baseListPageWrapper = object : BaseListPageWrapper<SysDept>(this) {

            override fun onLoadMore() {
                this@DeptListVmBox.loadMore()
            }
        }
    }

    override fun getDataListSlcObserver(): SlcObserver<PageModel<SysDept>> {
        return baseListPageWrapper.dataListSlcObserver
    }

    override fun getLoadMoreDataFormat3(): LoadMoreDataFormat3 {
        return baseListPageWrapper.loadMoreDataFormat3
    }

    override fun refresh() {
        baseListPageWrapper.refresh()
    }

    override fun onSucceed(data: PageModel<SysDept>) {
        this.loadMoreDataFormat3.formatSimple(dataList, data)
        dataListOf.notifyChange()
    }

    override fun onError(errorCode: Int, errorMessage: String?) {
        onFailed(errorCode, errorMessage)
        this.loadMoreDataFormat3.loadMoreFail()
    }

    final override fun loadMore() {
        super.loadMore()
    }

    override fun onLoadMore() {
        loadMoreTree()
    }
    private fun getTreeId(): Long {
        return try {
            mTreeId.toLong()
        } catch (e: NumberFormatException) {
            0
        }
    }


    override fun loadMoreTree() {
        DeptServiceRepository.page(getTreeId(), loadMoreDataFormat3.offset)
            .to(bindToLifecycle())
            .subscribe(dataListSlcObserver)
    }

    override fun leafClick(index: Int, data: SysDept) {
        showTreeClickUiOf.value = BundleBuilder.create().build().apply {
            putLong(ConstantsTree.KEY_TREE_ID, data.deptId)
            putString(ConstantsTree.KEY_TREE_NAME, data.deptName)
        }
    }
}